﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace DFGK_WMS.Repository
{
    public class DepartmentRepository : BaseRepository<TDepartment>, IDepartmentRepository
    {
        public DepartmentRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }


        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public List<Menuitem> GetDepartment()
        {
            var list = Context.TDepartments.AsQueryable();
            list = list.OrderBy(x => x.ParentId);
            var mmlist = list.FirstOrDefault();
            return GetMenuitems(list.ToList(), (int)mmlist.ParentId);
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<Menuitem> GetMenuitems(List<TDepartment> list, int pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x => new Menuitem
            {
                value=x.Id,
                label=x.DepartmentName,
                parent=x.ParentId,
                children= GetMenuitems(list,x.Id)
            }).ToList();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddDepartment(DepartmentDto dto)
        {
            try
            {
                var obj = Context.TDepartments.AsNoTracking().FirstOrDefault(x => x.DepartmentCode == dto.DepartmentCode);
                if (obj!=null)
                {
                    return false;
                }
                TDepartment ment = new TDepartment()
                {
                    DepartmentCode = dto.DepartmentCode,
                    DepartmentName = dto.DepartmentName,
                    ParentId = dto.ParentId,
                    Contact = dto.Contact,
                    ContactMobile = dto.ContactMobile,
                    Status = dto.Status,
                    Remark = dto.Remark,
                    CreateDate = DateTime.Now,
                    CreateUserId = dto.NowUserId,
                    CreateUserName = dto.NowUserRealName
                };
                Context.TDepartments.Add(ment);
                Context.SaveChanges();
                foreach (var item in dto.OwnerIds.Split(','))
                {
                    TDepartmentOwner depown = new TDepartmentOwner()
                    {
                        DepartmentId = ment.Id,
                        OwnerId = Convert.ToInt32(item)
                    };
                    Context.TDepartmentOwners.Add(depown);
                    Context.SaveChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdateDepartment(DepartmentDto dto)
        {
            using(var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    var obj = Context.TDepartments.AsNoTracking().FirstOrDefault(x => x.Id != dto.Id && x.DepartmentCode == dto.DepartmentCode);
                    if (obj != null) 
                    {
                        return false;
                    }
                    TDepartment ment = new TDepartment()
                    {
                        Id=dto.Id,
                        DepartmentCode = dto.DepartmentCode,
                        DepartmentName = dto.DepartmentName,
                        ParentId = dto.ParentId,
                        Contact = dto.Contact,
                        ContactMobile = dto.ContactMobile,
                        Status = dto.Status,
                        Remark = dto.Remark,
                        ModifyDate = DateTime.Now,
                        ModifyUserId = dto.NowUserId,
                        ModifyUserName = dto.NowUserRealName,
                        CreateDate = dto.CreateDate,
                        CreateUserId = dto.NowUserId,
                        CreateUserName = dto.NowUserRealName
                    };
                    Context.TDepartments.Update(ment);
                    var list = Context.TDepartmentOwners.Where(x => x.DepartmentId == dto.Id);
                    if (list.Any())
                    {
                        Context.TDepartmentOwners.RemoveRange(list);                     
                    }
                    foreach (var item in dto.OwnerIds.Split(','))
                    {
                        TDepartmentOwner depown = new TDepartmentOwner()
                        {
                            DepartmentId = ment.Id,
                            OwnerId = Convert.ToInt32(item)
                        };
                        Context.TDepartmentOwners.Add(depown);
                    }
                    tran.Commit();
                    return Context.SaveChanges() > 0;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
            
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelDepartment(int ids)
        {
            using(var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    var dep = Context.TDepartments.Find(ids);
                    if(dep!=null)
                    {
                        var list = Context.TDepartmentOwners.Where(x => x.DepartmentId == ids);
                        if (list.Any())
                        {
                            Context.TDepartmentOwners.RemoveRange(list);
                        }
                        Context.TDepartments.Remove(dep);
                    }
                    bool result = Context.SaveChanges()>0;
                    tran.Commit();
                    return result;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }

            }
        }

        /// <summary>
        /// 部门分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<TDepartment> GetDepartments(string name, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var list = Context.TDepartments.AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    list = list.Where(x => x.DepartmentName.Contains(name));
                }
                totalCount = list.Count();
                list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);               
                return list.ToList();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public DepartmentDto GetDepartment(int ids)
        {
            var dobj = Context.TDepartments.Find(ids);
            if(dobj!=null)
            {
                DepartmentDto m = new DepartmentDto();
                m= Mapper.Map<DepartmentDto>(dobj);
                var doobj = Context.TDepartmentOwners.Where(x => x.DepartmentId == dobj.Id);
               if(doobj.Any())
                {
                    foreach (var item in doobj)
                    {
                        m.OwnerIds += item.OwnerId + ",";
                    }
                    m.OwnerIds = m.OwnerIds.TrimEnd(',');
                    
                }
                return m;
            }
            return null;
        }
    }
}
